<template>
    <div>
        <!-- 按钮区域 -->
        <el-row class="button-group" type="flex" justify="space-between" align="middle">
            <el-col>
                <el-button type="primary" size="medium" icon="el-icon-plus" @click=openAddDialog>新增线体</el-button>
                <el-button type="danger" size="medium" icon="el-icon-delete"
                    @click="deleteLine(currentLine.id)">删除当前线</el-button>
                <el-button type="success" size="medium" icon="el-icon-refresh"
                    @click=openEditDialog(currentLine)>更新当前线</el-button>
            </el-col>
        </el-row>

        <el-row>
            <!-- v-model="activeLine" 会给activeLine一个初始值"0" -->
            <el-tabs type="border-card" v-model="activeLine">
                <el-tab-pane v-for="line in lines" :key="line.id" :label="line.name" :name="line.id">
                    <div>
                        <!-- <h2>{{ line.name }}</h2> -->
                        <p>{{ line.name }} - {{ line.description }}</p>
                        <el-button @click="addMachine" size="medium" type="primary" icon="el-icon-plus"
                            style="margin-bottom: 10px;">新增机器</el-button>
                        <el-table :data="line.machines" style="width: 100%" :key="activeLine" border
                            :header-cell-style="headerStyleEvent">
                            <el-table-column prop="machineCategory" label="机器类别" align="center"></el-table-column>
                            <el-table-column prop="machineType" label="机器型号" align="center"></el-table-column>
                            <el-table-column prop="machineName" label="名称" align="center"></el-table-column>
                            <el-table-column prop="machineDesc" label="描述" align="center"></el-table-column>
                            <el-table-column prop="positionInfo" label="位置" align="center"></el-table-column>
                            <el-table-column label="操作" align="center">
                                <template slot-scope="scope">
                                    <el-button size="mini" type="text" @click="editMachine(scope.row)">编辑</el-button>
                                    <el-button size="mini" type="text" @click="deleteMachine(scope.row.machineId)"
                                        style="color:#f56c6c">删除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </el-tab-pane>
            </el-tabs>
        </el-row>
        <!-- 新增线体 更新线体-->
        <el-dialog :title="isEdit ? '更新线体' : '新增线体'" :visible.sync="addLineDialogShow" width="40%" @close="resetForm">
            <el-form ref="addform" :model="addForm" label-width="80px" :rules="addrules">
                <el-form-item label="线体名称" prop="name">
                    <el-input v-model="addForm.name"></el-input>
                </el-form-item>
                <el-form-item label="线体描述" prop="desc">
                    <el-input v-model="addForm.desc"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addLineDialogShow = false">取 消</el-button>
                <el-button type="primary" @click="isEdit ? handleUpdateLine(currentLine.id) : handleAddLine()">确
                    定</el-button>
            </span>
        </el-dialog>
        <!-- 新增 编辑机器 -->
        <el-dialog :title="isEditMachine ? '编辑机器' : '新增机器'" :visible.sync="machineDialogShow" width="50%"
            @close="resetMachineForm">
            <el-form ref="machineForm" :model="machineForm" label-width="80px" :rules="machineRules">
                <!-- 机器类别 -->
                <el-form-item label="机器类别" prop="equipCategory">
                    <el-select v-model="machineForm.equipCategory" clearable style="width:100%;"
                        @change="handleCategoryChange">
                        <el-option v-for="item in machineCategoryOptions" :key="item.value" :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>

                <!-- 机器型号 - 编辑模式下显示下拉选择 -->
                <el-form-item label="机器型号" prop="machineType">
                    <el-select v-model="machineForm.machineType" style="width:100%;">
                        <el-option v-for="item in machineTypeOptions" :key="item.value" :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select>
                    <el-tag type="warning" style="white-space:break-spaces;height:auto;line-height:1.5em;">
                        [如果不存在要选择的机器型号，请先在“设备类型管理”中添加对应的型号]
                    </el-tag>
                </el-form-item>

                <!-- 机器型号 - 新增模式下显示输入框 -->
                <!-- <el-form-item label="机器型号" prop="machineType" v-if="!isEditMachine">
                    <el-input v-model="machineForm.machineType"></el-input>
                </el-form-item> -->

                <!-- 机器名称 -->
                <el-form-item label="机器名称" prop="name">
                    <el-input v-model="machineForm.name"></el-input>
                </el-form-item>

                <!-- 机器描述 -->
                <el-form-item label="机器描述" prop="desc">
                    <el-input v-model="machineForm.desc"></el-input>
                </el-form-item>

                <!-- 位置 -->
                <el-form-item label="位置" prop="positionInfo">
                    <el-input v-model="machineForm.positionInfo"></el-input>
                </el-form-item>
            </el-form>

            <!-- Dialog 底部按钮 -->
            <span slot="footer" class="dialog-footer">
                <el-button @click="machineDialogShow = false">取 消</el-button>
                <el-button type="primary" @click="isEditMachine ? handleUpdateMachine() : handleAddMachine()">确
                    定</el-button>
            </span>
        </el-dialog>


    </div>
</template>


<script>
import { getLineMachine, addLineData, deleteLineData, updateLineData, deleteMachineData, updateMachineData, addMachineData, FeachGetEquipTypes } from '@/network/linemachine'
export default {
    data() {
        return {
            activeLine: '', // 默认显示的生产线ID
            addLineDialogShow: false,
            machineDialogShow: false,
            addForm: {},
            machineForm: {
                equipCategory: '',
                machineType: '',
                name: '',
                desc: '',
                positionInfo: ''
            },
            isEdit: false, // 区分是新增还是更新
            isEditMachine: false,
            lines: [],
            addrules: {
                name: [
                    { required: true, message: '请输入线体名称', trigger: 'blur' },
                    { min: 1, max: 20, message: '长度在 1 到 30 个字符', trigger: 'blur' }
                ],
            },
            cascaderOptions: [],
            machineCategoryOptions: [{
                value: '贴片机',
                label: '贴片机'
            }, {
                value: '印刷机',
                label: '印刷机'
            },],
            machineTypeOptions: [],
            machineRules: {

                equipCategory: [{ required: true, message: '请选择机器类别', trigger: 'change' }],
                machineType: [{ required: true, message: '请输入机器型号', trigger: 'blur' }],
                name: [{ required: true, message: '请输入机器名称', trigger: 'blur' }],
                desc: [{ message: '请输入机器描述', trigger: 'blur' }],
                positionInfo: [{ message: '请输入机器位置', trigger: 'blur' }],
            },
        };
    },
    mounted() {
        this.getLineMachineData()
        this.getEquipTypes()
    },
    computed: {
        currentLine() {
            return this.lines.find(line => line.id === this.activeLine);
        }
    },
    methods: {
        async getLineMachineData() {
            try {
                const res = await getLineMachine();
                console.log(res); // 打印返回的结果以检查结构
                this.lines = res.data.map(line => ({
                    id: line.lineId.toString(),
                    name: line.lineName,
                    description: line.lineDesc,
                    machines: line.layouts.map(layout => ({
                        machineCategory: layout.machineCategory,
                        machineType: layout.machineType,
                        machineName: layout.machineName,
                        machineDesc: layout.machineDesc,
                        positionInfo: layout.positionInfo,
                        machineId: layout.machineId
                    }))
                }));

                // 设置默认选中的生产线 [初始会给activeLine默认值'0'] (!this.activeLine || this.activeLine==='0')
                // 该不包含tab-name时才默认
                if (this.lines.length > 0 && this.lines.map(l => l.id).indexOf(this.activeLine) < 0) {
                    this.activeLine = this.lines[0].id;
                }

                // this.$nextTick(() => {
                //     this.$forceUpdate();
                // });
            } catch (error) {
                console.error(error);
            }
        },

        addMachine() {
            this.isEditMachine = false,
                this.machineForm = {
                    equipCategory: '',
                    machineType: '',
                    name: '',
                    desc: '',
                    positionInfo: ''
                }
            this.machineDialogShow = true
        },
        async handleAddMachine() {

            const valid = await this.$refs['machineForm'].validate().catch(err => false);
            if (valid) {
                // 表单验证通过，执行新增线体请求
                this.machineForm.lineId = this.currentLine.id
                const res = await addMachineData(this.machineForm); // 确保使用的是 addForm 而不是 this.form
                if (res.status === 200) {
                    // 新增成功后的提示
                    this.$message({
                        message: '新增成功',
                        type: 'success'
                    });
                    // 关闭对话框并重置表单
                    this.machineDialogShow = false;
                    this.getLineMachineData()
                    this.$refs['machineForm'].resetFields(); // 重置表单
                }
            }
            else {
                // 捕获异常并输出错误
                console.log('表单验证失败:');
            }
        },
        editMachine(row) {

            this.machineForm.id = row.machineId
            this.machineForm.equipCategory = row.machineCategory
            this.machineForm.machineType = row.machineType
            this.machineForm.name = row.machineName
            this.machineForm.desc = row.machineDesc
            this.machineForm.positionInfo = row.positionInfo

            // this.handleCategoryChange(row.machineCategory); 编辑时不需要
            this.isEditMachine = true
            this.machineDialogShow = true
        },
        // 编辑机器
        async handleUpdateMachine() {

            const valid = await this.$refs['machineForm'].validate().catch(err => false);
            if (valid) {
                // 表单验证通过，执行新增线体请求
                this.machineForm.lineId = this.currentLine.id
                const res = await updateMachineData(this.machineForm); // 确保使用的是 addForm 而不是 this.form
                if (res.status === 200) {
                    // 新增成功后的提示
                    this.$message({
                        message: '编辑成功',
                        type: 'success'
                    });
                    // 关闭对话框并重置表单
                    this.machineDialogShow = false;
                    this.getLineMachineData()
                    this.$refs['machineForm'].resetFields(); // 重置表单
                }
            }
            else {
                console.log('表单验证失败:');
            }
        },
        openAddDialog() {
            this.isEdit = false;
            this.addLineDialogShow = true;
            this.addForm = {};
        },

        // 打开更新对话框
        openEditDialog(line) {
            this.isEdit = true;
            this.addLineDialogShow = true;
            this.addForm = { id: line.id, name: line.name, desc: line.description }; // 将选中的线体数据填充到表单中
        },

        //删除机器
        async deleteMachine(id) {
            await this.$confirm('此操作将永久删除该机器, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            });
            await deleteMachineData({ id });
            this.$message({
                type: 'success',
                message: '删除成功!'
            });

            // 删除成功后更新线体列表
            this.getLineMachineData();

        },
        handleCategoryChange(value) {
            this.machineForm.machineType = ''
            // 当选择机器类别时，过滤出对应的机器型号选项
            const selectedCategoryData = this.cascaderOptions.find(item => item.equipCategory === value);
            if (selectedCategoryData) {
                // 提取当前选择的机器类别的型号数据
                this.machineTypeOptions = selectedCategoryData.machineData.map(machine => ({
                    value: machine.machineType,
                    label: machine.machineType
                }));


            } else {
                // 如果没有找到对应类别，清空型号选项
                this.machineTypeOptions = [];
            }
        },

        // 获取设备类别和机器类型数据
        async getEquipTypes() {
            try {
                const res = await FeachGetEquipTypes(); // 获取设备类型数据
                console.log(res);

                this.cascaderOptions = res.data; // 将数据保存到 cascaderOptions 中
                // 提取机器类别选项

            } catch (error) {
                console.error('获取机器数据失败:', error);
            }
        },
        // 添加线体
        async handleAddLine() {
            // 使用 try...catch 捕获整个逻辑中的异常

            // 等待表单验证结果
            const valid = await this.$refs['addform'].validate().catch(err => false);
            //.catch((err) => { console.log("validate catch:",err); return false; });
            if (valid) {
                console.log("this.addForm", this.addForm);

                // 表单验证通过，执行新增线体请求
                const res = await addLineData(this.addForm); // 确保使用的是 addForm 而不是 this.form
                console.log(res);
                if (res.status == 200) {
                    // 新增成功后的提示
                    this.$message({
                        message: '新增成功',
                        type: 'success'
                    });
                    // 关闭对话框并重置表单
                    this.addLineDialogShow = false;
                    this.getLineMachineData()
                    this.$refs['addform'].resetFields(); // 重置表单
                }
            }
            else {
                // 捕获异常并输出错误
                console.log('表单验证失败:');
            }
        },
        // 更新线体
        async handleUpdateLine() {
            console.log(this.addForm);
            this.$refs['addform'].validate(async (valid) => {
                if (valid) {

                    const res = await updateLineData(this.addForm);
                    if (res.status == 200) {
                        this.$message({
                            message: '更新成功',
                            type: 'success'
                        });
                        this.addLineDialogShow = false;
                        // 重新加载线体数据
                        this.getLineMachineData()
                    }
                    else {
                        console.warn('更新出错');
                    }
                } else {
                    console.log('表单校验失败');
                    return false;
                }
            });
        },

        headerStyleEvent() {
            if (this.$store.state.theme.useCustomTheme === "7-gpx") {
                return { background: '#f5f5f5', color: '#2F4F4F' };
            } else {
                return { background: '#eef1f6', color: '#606266' }
            }
        },
        async deleteLine(id) {

            // 弹出确认框
            const confirm = await this.$confirm('此操作将永久删除该线体, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            });
            // 如果是取消操作，不执行任何操作
            if (confirm == 'cancel') {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
                return;
            }
            // 用户确认后执行删除请求
            const res = await deleteLineData({ id });
            if (res.status == 200) {
                this.$message({
                    type: 'success',
                    message: '删除成功!'
                });

                // 删除成功后更新线体列表
                this.getLineMachineData();
            }
            // else {
            //     this.$message({
            //         type: 'error',
            //         message: '删除失败，' + res.message
            //     });
            // }

        },
        resetForm() {
            this.$refs['addform'].resetFields();
        },
        resetMachineForm() {
            this.$refs['machineForm'].resetFields();
        }
    }
}


</script>
<style scoped>
.button-group {
    /* margin-bottom: 20px; */
    border-bottom: 1px solid #ebeef5;
    padding-bottom: 10px;
}

.button-group .el-button {
    margin-right: 10px;
}
</style>
